package com.rocksea.app.fragment;


import android.content.Context;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.PopupMenu;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.rocksea.app.BaseFragment;
import com.rocksea.app.R;
import com.rocksea.app.db.DbCenter;
import com.rocksea.app.db.SonicWave.SonicWave;
import com.rocksea.app.event.UpDateSonicWave;
import com.rocksea.app.tasks.Temp;
import com.rocksea.app.utils.PerUtils;
import com.rocksea.app.weight.DividerListItemDecoration;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;
import butterknife.InjectView;

/**
 * @author Administrator
 * @date 2017/11/17
 */

public class SectionInfoAFragment extends BaseFragment {

    @InjectView(R.id.Node_List)
    RecyclerView mRecyclerView;
    @InjectView(R.id.Item_View)
    View mView;
    private String sectionId;

    public SectionInfoAFragment()
    {

    }
    public static SectionInfoAFragment newInstance(Bundle bundle)
    {
        SectionInfoAFragment sectionInfoAFragment = new SectionInfoAFragment();
        sectionInfoAFragment.setArguments(bundle);
        return sectionInfoAFragment;
    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onNotificationList(UpDateSonicWave upDateSonicWave)
    {
        if (Temp.getSonicWave()!=null)
        {
            ArrayList<SonicWave.SonicWaveData> fromMenSonicWave = new ArrayList<>();
            for (int i = 0; i < Temp.getSonicWave().SonicWaveDatas.size(); i++)
            {
                if (Temp.getSonicWave().SonicWaveDatas.get(i).sectionId.equals(sectionId))
                    fromMenSonicWave.add(Temp.getSonicWave().SonicWaveDatas.get(i));
            }
            handSonicWaveData(fromMenSonicWave,new ArrayList<Integer>());
        }
    }


    @Override
    protected void initView()
    {
        if (!EventBus.getDefault().isRegistered(this))
            EventBus.getDefault().register(this);
        mView.setBackgroundColor(ContextCompat.getColor(getContext(),R.color.colorPrimary));
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        mRecyclerView.setLayoutManager(layoutManager);
        mRecyclerView.addItemDecoration(new DividerListItemDecoration(getContext(),DividerListItemDecoration.VERTICAL_LIST));
    }
    @Override
    protected void initData() {
        loading();
        sectionId = getArguments().getString(SetionInfoFragment.SECTION_UUID);
        AsyQueryWaveDataTask task = new AsyQueryWaveDataTask(sectionId);
        task.execute();
    }
    @Override
    protected void requestAgain() {

    }
    @Override
    protected int getContentViewId() {
        return R.layout.node_list;
    }

    private class NodeListAdapter extends RecyclerView.Adapter<NodeViewHodler>
    {

        private List<SonicWave.SonicWaveData> sonicWaveDatas;
        private Context context;
        private ArrayList<Integer> distinctDepth;

        private NodeListAdapter(List<SonicWave.SonicWaveData> sonicWaveDatas, Context context,ArrayList<Integer> distinctDepth)
        {
            this.sonicWaveDatas = sonicWaveDatas;
            this.context = context;
            this.distinctDepth = distinctDepth;
        }

        @Override
        public NodeViewHodler onCreateViewHolder(ViewGroup viewGroup, int i)
        {
            View mBootView = LayoutInflater.from(context).inflate(R.layout.node_list_litem,viewGroup,false);
            return new NodeViewHodler(mBootView);
        }

        @Override
        public void onBindViewHolder(final NodeViewHodler nodeViewHodler, final int i)
        {
            final SonicWave.SonicWaveData data =  sonicWaveDatas.get(i);
            if (distinctDepth!=null)
            {
                if (distinctDepth.contains(data.depth))
                    nodeViewHodler.mItemView.setBackgroundColor(Color.YELLOW);
                else
                    nodeViewHodler.mItemView.setBackgroundColor(Color.WHITE);
            }
            else
                nodeViewHodler.mItemView.setBackgroundColor(Color.WHITE);

            if (data.isValid==0)
            {
                nodeViewHodler.tvValid.setText("有效");
                nodeViewHodler.tvValid.setTextColor(ContextCompat.getColor(context,R.color.colorPrimary));

            }
            else
            {
                nodeViewHodler.tvValid.setText("无效");
                nodeViewHodler.tvValid.setTextColor(Color.RED);
            }
            nodeViewHodler.tvDepth.setText(String.format("%.2f",(data.depth/(float)1000)));
            nodeViewHodler.tvA.setText(String.format("%.1f",data.A));
            nodeViewHodler.tvT.setText(String.format("%.1f",data.T));
            nodeViewHodler.tvValid.setOnClickListener(new View.OnClickListener()
            {
                @Override
                public void onClick(View v) {
                    PopupMenu popupMenu = new PopupMenu(context, nodeViewHodler.tvT);
                    popupMenu.getMenuInflater().inflate(R.menu.context_menu, popupMenu.getMenu());
                    if (data.isValid == 0) {
                        popupMenu.getMenu().findItem(R.id.Choose_Valid).setTitle("标记为无效");
                    } else {
                        popupMenu.getMenu().findItem(R.id.Choose_Valid).setTitle("标记为有效");
                    }
                    popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
                        @Override
                        public boolean onMenuItemClick(MenuItem menuItem)
                        {
                            switch (menuItem.getItemId())
                            {
                                case R.id.Choose_Valid:
                                    if (sonicWaveDatas.get(i).isValid==0)
                                    {
                                        DbCenter.makeScWaveAsIsValid(sonicWaveDatas.get(i).uuid,1);
                                        sonicWaveDatas.get(i).isValid = 1;
                                        notifyDataChanged();
                                    }
                                    else
                                    {
                                        DbCenter.makeScWaveAsIsValid(sonicWaveDatas.get(i).uuid,0);
                                        sonicWaveDatas.get(i).isValid = 0;
                                        notifyDataChanged();
                                    }
                                    break;
                            }
                            return false;
                        }
                    });
                    popupMenu.show();
                }

            });
        }
        @Override
        public int getItemCount()
        {
            return sonicWaveDatas.size();
        }

        private void notifyDataChanged()
        {
            notifyDataSetChanged();
        }
    }

    private class NodeViewHodler extends RecyclerView.ViewHolder
    {
        private TextView tvDepth,tvT,tvA,tvValid;
        private View mItemView;
        private NodeViewHodler(View itemView)
        {
            super(itemView);
            tvDepth = (TextView) itemView.findViewById(R.id.Depth);
            tvT = (TextView) itemView.findViewById(R.id.T);
            tvA = (TextView) itemView.findViewById(R.id.A);
            tvValid = (TextView) itemView.findViewById(R.id.Valid);
            mItemView = itemView.findViewById(R.id.Item_View);
        }
    }

    public class AsyQueryWaveDataTask extends AsyncTask<Void,Void, List<SonicWave.SonicWaveData>>
    {

        private String baseInfoId;
        private ArrayList<Integer> distinctDepth;

        private AsyQueryWaveDataTask(String baseInfoId)
        {
            this.baseInfoId = baseInfoId;
        }
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }
        @Override
        protected List<SonicWave.SonicWaveData> doInBackground(Void... params)
        {
            distinctDepth = DbCenter.mScDbHelper.queryDistinctData(baseInfoId);
            if (Temp.getSonicWave()!=null)
            {
                ArrayList<SonicWave.SonicWaveData> fromMenSonicWave = new ArrayList<>();
                for (int i = 0; i < Temp.getSonicWave().SonicWaveDatas.size(); i++)
                {
                    if (Temp.getSonicWave().SonicWaveDatas.get(i).sectionId.equals(baseInfoId))
                        fromMenSonicWave.add(Temp.getSonicWave().SonicWaveDatas.get(i));
                }

                return  fromMenSonicWave;
            }
            return DbCenter.mScDbHelper.querySonicWaveData(baseInfoId);
        }

        @Override
        protected void onPostExecute( List<SonicWave.SonicWaveData> sonicWaveDatas)
        {
            super.onPostExecute(sonicWaveDatas);
            handSonicWaveData(sonicWaveDatas,distinctDepth);
        }
    }

    private void handSonicWaveData(List<SonicWave.SonicWaveData> sonicWaveDatas,ArrayList<Integer> distinctDepth)
    {
        if(sonicWaveDatas==null)
        {
            loadFailed();
            return;
        }
        if (sonicWaveDatas.size()==0)
        {
            loadFailed();
            mErrorText.setText("未找到数据");
            return;
        }
        NodeListAdapter adapter = new NodeListAdapter(sonicWaveDatas,getContext(),distinctDepth);
        mRecyclerView.setAdapter(adapter);
        loadCompleted();
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
